package com.tqyan.service.transfer;

import com.alibaba.fastjson.JSONObject;
import com.tqyan.model.dto.WechatUserDTO;
import com.tqyan.model.exp.DefaultException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;

/**
 * @description 微信服务
 * <p> <功能详细描述> </p>
 *
 * @author 陈晨
 * @date 2023/4/11 17:17
 */
@Component
@Slf4j
public class WechatService {
    //sdk 与微信服务器交互默认使用该配置，携带 appid 、secret
    private static final String APP_ID = "wxaf00cbb6ccc9caf1";
    private static final String APP_SECRET = "0e86c378b32c18d65e7cc7c21e3650c1";
    private static final String GRANT_TYPE = "authorization_code";

    /**
     * @description 发送get请求
     * <p> <功能详细描述> </p>
     *
     * @author 陈晨
     * @date 2023/4/11 17:15
     */
    private String sendGet(String url) throws IOException {
        StringBuilder result = new StringBuilder();
        BufferedReader in = null;
        try {
            URL realUrl = new URL(url);
            // 打开和URL之间的连接
            URLConnection connection = realUrl.openConnection();
            // 设置通用的请求属性
            connection.setRequestProperty("accept", "*/*");
            connection.setRequestProperty("connection", "Keep-Alive");
            connection.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            // 建立实际的连接
            connection.connect();
            // 定义 BufferedReader输入流来读取URL的响应
            in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            String line;
            while ((line = in.readLine()) != null) {
                result.append(line);
            }
            return result.toString();
        } finally {
            try {
                if (in != null) {
                    in.close();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * @description 获取微信用户信息
     * <p> <功能详细描述> </p>
     *
     * @author 陈晨
     * @date 2023/4/11 17:15
     */
    public WechatUserDTO getWechatUserInfo(String code) throws IOException {
        String url = "https://api.weixin.qq.com/sns/jscode2session"
                + "?appid=" + APP_ID
                + "&secret=" + APP_SECRET
                + "&js_code=" + code
                + "&grant_type=" + GRANT_TYPE;
        JSONObject result = JSONObject.parseObject(sendGet(url));
        log.info("[微信] url={}, result={}, 获取微信用户信息", url, result);
        if (null != result.get("errcode")) {
            int errorCode = result.getInteger("errcode");
            if (40029 == errorCode) {
                throw new DefaultException("微信登录校验码已失效");
            }
            if (45011 == errorCode) {
                throw new DefaultException("请稍后再试");
            }
            if (40226 == errorCode) {
                throw new DefaultException("微信号存在风险, 禁止授权");
            }
        }
        if (null == result.get("openid")) {
            throw new DefaultException("微信登录失败: " + result);
        }
        WechatUserDTO wechatUser = new WechatUserDTO();
        wechatUser.setOpenId((String) result.get("openid"));
//        wechatUser.setNickname((String) result.get("nickname"));
//        wechatUser.setPhone((String) result.get("phone"));
        return wechatUser;
    }

}


